const dotenv = require('dotenv');
const path = require('path');
const Joi = require('joi');

dotenv.config({ path: path.join(__dirname, '../../.env') });

// 定义环境变量验证schema
const envVarsSchema = Joi.object()
  .keys({
    NODE_ENV: Joi.string().valid('production', 'development', 'test').required(),
    PORT: Joi.number().default(3000),
    MONGODB_URL: Joi.string().required().description('MongoDB连接字符串'),
    JWT_SECRET: Joi.string().required().description('JWT密钥'),
    JWT_ACCESS_EXPIRATION_MINUTES: Joi.number().default(4320).description('JWT访问令牌过期时间（分钟）'),
    JWT_REFRESH_EXPIRATION_DAYS: Joi.number().default(30).description('JWT刷新令牌过期时间（天）'),
    JWT_RESET_PASSWORD_EXPIRATION_MINUTES: Joi.number()
      .default(10)
      .description('JWT重置密码令牌过期时间（分钟）'),
    JWT_VERIFY_EMAIL_EXPIRATION_MINUTES: Joi.number()
      .default(10)
      .description('JWT验证邮箱令牌过期时间（分钟）'),
    REDIS_HOST: Joi.string().description('Redis主机地址'),
    REDIS_PORT: Joi.number().description('Redis端口'),
    REDIS_PASSWORD: Joi.string().allow('').description('Redis密码'),
    WECHAT_APP_ID: Joi.string().default('wx0515aa35c9176d6d').description('微信小程序AppID'),
    WECHAT_APP_SECRET: Joi.string().default('2437f8fad9148134465162d90c04db2d').description('微信小程序AppSecret'),
  })
  .unknown();

const { value: envVars, error } = envVarsSchema.prefs({ errors: { label: 'key' } }).validate(process.env);

if (error) {
  throw new Error(`环境变量验证错误: ${error.message}`);
}

// 配置对象
module.exports = {
  env: envVars.NODE_ENV,
  port: envVars.PORT,
  mongoose: {
    url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
  },
  jwt: {
    secret: envVars.JWT_SECRET,
    accessExpirationMinutes: envVars.JWT_ACCESS_EXPIRATION_MINUTES,
    refreshExpirationDays: envVars.JWT_REFRESH_EXPIRATION_DAYS,
    resetPasswordExpirationMinutes: envVars.JWT_RESET_PASSWORD_EXPIRATION_MINUTES,
    verifyEmailExpirationMinutes: envVars.JWT_VERIFY_EMAIL_EXPIRATION_MINUTES,
    redisTokenExpiryDays: 3, // Redis中token的过期时间（天）
  },
  redis: {
    host: envVars.REDIS_HOST,
    port: envVars.REDIS_PORT,
    password: envVars.REDIS_PASSWORD,
  },
  wechat: {
    appId: envVars.WECHAT_APP_ID,
    appSecret: envVars.WECHAT_APP_SECRET,
  },
}; 